package com.jack.lib.net.interceptor

import com.blankj.utilcode.util.EncryptUtils
import com.jack.lib.net.JNetManager
import com.jack.lib.net.cache.NetCache
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import okio.GzipSource
import java.net.SocketTimeoutException
import java.nio.charset.StandardCharsets

/**
 * author : chong.huang
 * create : 2021/12/30
 * desc   :
 */
abstract class JBaseResponseBodyInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url.toString()
        val response = chain.proceed(request)
        response.body?.let {
            it.source().request(Long.MAX_VALUE)
            var buffer = it.source().buffer
            if ("gzip" == response.headers["Content-Encoding"]) {
                buffer = Buffer()
                buffer.writeAll(GzipSource(buffer.clone()))
            }
            val contentType = it.contentType()
            val charset = if (contentType?.charset(StandardCharsets.UTF_8) == null) {
                StandardCharsets.UTF_8
            } else {
                contentType.charset(StandardCharsets.UTF_8)
            }
            if (charset != null && it.contentLength() != 0L) {
                return intercept(response, url, buffer.clone().readString(charset))
            }
        }
        NetCache.remove(EncryptUtils.encryptMD5ToString(request.toString()))
        return response
    }

    abstract fun intercept(response: Response, url: String, body: String): Response

}